﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using Rabbit.BusinessLogicLayer;
using Rabbit.Model;
using Rabbit.Utils;

namespace MicroBlogClient
{
    /// <summary>
    /// Interaction logic for FriendsStatus.xaml
    /// </summary>
    public partial class FriendsStatus : PageBase
    {
        //#region Observable Collections
        //ObservableCollection<Status> FriendsStatusCollection = new ObservableCollection<Status>();
        //ObservableCollection<Status> PublicStatusCollection = new ObservableCollection<Status>();
        //#endregion

        public ObservableCollection<Status> FriendsStatusCollection { get; set; }
        public ObservableCollection<Status> PublicStatusCollection { get; set; }

        List<Status> FriendsStatusPool = new List<Status>();
         
        FriendStatusBL friendsStatusBL;
        PublicStatusBL publicStatusBL;

        public FriendsStatus()
        {
            FriendsStatusCollection = new ObservableCollection<Status>();
            PublicStatusCollection = new ObservableCollection<Status>();

            InitializeComponent();
            this.Loaded += new RoutedEventHandler(FriendsStatus_Loaded);
        }

        void FriendsStatus_Loaded(object sender, RoutedEventArgs e)
        {
            DataContext = this;
        }

        public override void StartLoading()
        {
            base.StartLoading();
            friendsStatusBL = new FriendStatusBL(MySettings.UpdateInterval.Value);
            publicStatusBL = new PublicStatusBL(MySettings.UpdateInterval.Value);

            //this is used to update the status list
            friendsStatusBL.MainMessageList = FriendsStatusCollection;

            friendsStatusBL.OnPublishAPICallTooFrequent = base.OnCallAPITooFrequentExceptionOccured;
            publicStatusBL.OnPublishAPICallTooFrequent = base.OnCallAPITooFrequentExceptionOccured;

            friendsStatusBL.OnUnknownExceptionOccured = base.OnUnHandledExceptionOccured;
            publicStatusBL.OnUnknownExceptionOccured = base.OnUnHandledExceptionOccured;

            friendsStatusBL.OnMessageInitialized = OnFriendsStatusInitialized;
            friendsStatusBL.OnNewMessageReceived = NewFriendsStatusReceived;

            publicStatusBL.OnMessageInitialized = OnPublicStatusInitialized;
            publicStatusBL.OnNewMessageReceived = NewPublicStatusReceived;

            ShowProcessingMessage("正在加载...");
            BeginInitializeMessage();
        }
        private void OnFriendsStatusInitialized(List<Status> messageList)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                messageList.ForEach(s => FriendsStatusCollection.Add(s));
            }), System.Windows.Threading.DispatcherPriority.Background);

            base.HideMessage();
            //base.ShowSuccessfulMessage("加载完成");
        }

        private void OnPublicStatusInitialized(List<Status> messageList)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                messageList.ForEach(s => PublicStatusCollection.Add(s));
            }), System.Windows.Threading.DispatcherPriority.Background);
            //base.ShowSuccessfulMessage("加载完成");
            base.HideMessage();

        }

        void NewFriendsStatusReceived(List<Status> messageList)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                //refresh the create at showed on the list
                FriendsStatusCollection.ForEach(s => s.CreatedAt = s.CreatedAt); 

                //remove the status that has already existed in current friends status collection
                //or statuses that was forwarded from me
                messageList.RemoveAll(status =>
                    FriendsStatusCollection.Find(t => t.Id == status.Id) != -1 
                    || status.InReplyToUserId == UserBL.CurrentUser.Id);

                if (messageList.Count == 0)
                {
                    return;
                }

                MessagePoolCount += messageList.Count;
                FriendsStatusPool.InsertRange(0, messageList);

                if (FriendsStatusPool.Count > MaxRecordsCountShowed)
                {
                    FriendsStatusPool.RemoveRange(MaxRecordsCountShowed, FriendsStatusPool.Count - MaxRecordsCountShowed);
                }
                TryPopupMessage<Status>(MySettings.PopupForNewStatus,
                    new Action<object, MouseButtonEventArgs>((o, args) =>
                    {
                        this.Dispatcher.BeginInvoke((Action)delegate()
                        {
                            (App.Current.MainWindow as MainWindow).FlushFriendsStatusPool(o, args);
                        });
                    }), 
                    "微博",
                    messageList[0]);
            }), System.Windows.Threading.DispatcherPriority.Background);
        }

        void NewPublicStatusReceived(List<Status> messageList)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                messageList.RemoveAll(status => PublicStatusCollection.Find(s=>s.Id == status.Id) != -1);
                messageList.ForEach(s =>{
                    PublicStatusCollection.Insert(0, s);
                    if (PublicStatusCollection.Count > MaxRecordsCountShowed)
                    {
                        PublicStatusCollection.RemoveAt(PublicStatusCollection.Count - 1);
                    }
                }); 
            }), System.Windows.Threading.DispatcherPriority.Background);
        }
    
        public override void DoWork(object obj = null)
        {
            if (obj==null)
            {
                if (FriendsStatusPool.Count == 0)
                {
                    return;
                }
                App.StopTwinkleSysTrayIcon();
                tabStatusesContent.SelectedItem = tabItemFriendsStatus;

                FriendsStatusCollection.InsertRange(FriendsStatusPool, MaxRecordsCountShowed);
                lstFriendsStatusList.ScrollIntoView(FriendsStatusCollection[0]);
                FriendsStatusPool.Clear();
                NotifyMainWindowNewMessageCountChanged(0);
                MessagePoolCount = 0;
            }
            else if(obj.GetType() == typeof(Status))
            {
                FriendsStatusCollection.Insert(0,obj as Status);
            }
        }

        protected override void NotifyMainWindowNewMessageCountChanged(int messageCount)
        {
            (App.Current.MainWindow as MainWindow).NewFriendsStatusCount = messageCount;
        }
  
        private void tabStatusesContent_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tabStatusesContent.SelectedIndex == 1 && PublicStatusCollection.Count == 0)
            {
                base.ShowProcessingMessage("正在加载...");
                publicStatusBL.StartFetchingMessage();
            }
        }

        public override void BeginInitializeMessage()
        {
            friendsStatusBL.StartFetchingMessage();
        }

        public override void pager_OnFirstPageClick(object sender, RoutedEventArgs e)
        {
            ShowProcessingMessage("正在加载...");
            Action fetching = () =>
            {
                try
                {
                    List<Status> fetchedMessage = friendsStatusBL.GetFirstPageMessage();
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        FriendsStatusCollection.Clear();
                        fetchedMessage.ForEach(c => FriendsStatusCollection.Add(c));
                        pager.CanPreviousePageClick = friendsStatusBL.CanGetPreviousePage;
                        pager.CanNextPageClick = friendsStatusBL.CanGetNextPage;
                        if (FriendsStatusCollection.Count > 0)
                        {
                            lstFriendsStatusList.ScrollIntoView(FriendsStatusCollection[0]);
                        }
                    }));
                    HideMessage();
                    //ShowSuccessfulMessage("加载完成");
                }
                catch (Exception ex)
                {
                    ShowFailedMessage("获取失败:" + ex.Message);
                }
            };

            fetching.BeginInvoke(null, null);
        }

        public override void pager_OnPreviousePage(object sender, RoutedEventArgs e)
        {
            ShowProcessingMessage("正在加载...");
            Action fetching = () =>
            {
                try
                {
                    List<Status> fetchedMessage = friendsStatusBL.GetPreviousePageMessage();
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        FriendsStatusCollection.Clear();
                        fetchedMessage.ForEach(c => FriendsStatusCollection.Add(c));
                        pager.CanPreviousePageClick = friendsStatusBL.CanGetPreviousePage;
                        pager.CanNextPageClick = friendsStatusBL.CanGetNextPage;
                        if (FriendsStatusCollection.Count > 0)
                        {
                            lstFriendsStatusList.ScrollIntoView(FriendsStatusCollection[0]);
                        }
                    }));
                    HideMessage();
                    //ShowSuccessfulMessage("加载完成");
                }
                catch (Exception ex)
                {
                    ShowFailedMessage("获取失败:" + ex.Message);
                }
            };

            fetching.BeginInvoke(null, null);
        }

        public override void pager_OnNextPageClick(object sender, RoutedEventArgs e)
        {
            ShowProcessingMessage("正在加载...");
            Action fetching = () =>
            {
                try
                {
                    List<Status> fetchedMessage = friendsStatusBL.GetNextPageMessage();
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        FriendsStatusCollection.Clear();
                        fetchedMessage.ForEach(c => FriendsStatusCollection.Add(c));
                        pager.CanPreviousePageClick = true;
                        pager.CanNextPageClick = friendsStatusBL.CanGetNextPage;
                        if (FriendsStatusCollection.Count > 0)
                        {
                            lstFriendsStatusList.ScrollIntoView(FriendsStatusCollection[0]);
                        }
                    }));
                    HideMessage();
                    //ShowSuccessfulMessage("加载完成");
                }
                catch (Exception ex)
                {
                    ShowFailedMessage("获取失败:" + ex.Message);
                }
            };

            fetching.BeginInvoke(null, null);
        }

        public override void StopFetchingMessage()
        {
            if (friendsStatusBL != null)
            {
                friendsStatusBL.StopFetchingMessage();
                friendsStatusBL = null;
            }
            if (publicStatusBL != null)
            {
                publicStatusBL.StopFetchingMessage();
                publicStatusBL = null;
            }

            FriendsStatusPool.Clear();
            FriendsStatusCollection.Clear();
            PublicStatusCollection.Clear();
        }
    }
}
